<template>
  <div class="app-container">
    <div
      v-if="isShowFilterContainer"
      class="filter-container"
    >
      <el-input
        v-model="pagerequest.filter"
        :placeholder="L(keywordPlaceholder)"
        style="width: 200px;"
        class="filter-item"
        size="small"
        clearable
      />

      <el-select
        v-model="pagerequest.status"
        size="small"
        class="filter-item"
        placeholder="审批状态"
        clearable
      >
        <el-option
          v-for="item in wfStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <slot name="FilterItems" />

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :loading="loading"
        size="small"
        @click="pageChange(1)"
      >
        {{ L('Find') }}
      </el-button>
      <el-button
        v-if="tableType == 'mine'"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        size="small"
        @click="onCreate"
      >
        新的申请
      </el-button>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :height="tableHeight"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        size="small"
        @sort-change="tableSortChange"
      >
        <el-table-column
          v-if="isShowEditDeleteButton"
          :label="L('Actions')"
          width="120"
        >
          <template slot-scope="scope">
            <el-dropdown
              size="small"
              trigger="click"
              @command="handleComand($event,scope.row)"
            >
              <el-button
                size="small"
                type="primary"
              >
                <i class="el-icon-setting el-icon--left" />操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="tableType == 'wait'"
                  command="edit"
                  icon="el-icon-edit"
                >处理</el-dropdown-item>
                <el-dropdown-item
                  v-else
                  command="edit"
                  icon="el-icon-search"
                >查看</el-dropdown-item>
                <!-- <el-dropdown-item
                  command="delete"
                  icon="el-icon-delete"
                >{{ L('Delete') }}</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

        <slot name="TableColumns" />

        <el-table-column
          prop="isFinish"
          label="状态"
        >
          <template slot-scope="{row}">
            <wfStatus :is-finish="row.isFinish" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="datatable-paging">
      <el-pagination
        :page-sizes="[10, 50, 100, 150]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        :current-page="currentPage"
        @size-change="pagesizeChange"
        @current-change="pageChange"
      />
    </div>

    <!-- 对话框 -->
    <div>
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogCreateOrEditVisible"
        width="980px"
        top="3vh"
        modal
        class="dialog-layout"
        modal-append-to-body
        append-to-body
        lock-scroll
        show-close
        :close-on-click-modal="false"
      >
        <el-tabs v-model="activeTag">
          <el-tab-pane
            label="表单信息"
            name="form"
          >
            <el-container :style="{height:containerHeight}">
              <el-container>
                <el-main>
                  <div v-if="dialogAction == 'edit' && ([0, 4].indexOf(isFinish) > -1)">
                    <el-tag size="mini" effect="light">当前处理人：<span style="color:#000">{{ makerList }}</span></el-tag>
                    <el-tag size="mini" effect="light">流程状态：<span style="color:#000">{{ activityName }}</span></el-tag>
                  </div>
                  <slot
                    name="ApplyOrVerificationForm"
                    :rdn="rdn"
                    :dialogAction="dialogAction"
                    :activityName="activityName"
                    :isActiveNode="isActiveNode"
                    :isActiveNo="isActiveNo"
                  />
                </el-main>
              </el-container>
              <el-aside v-if="verificationVisible" width="200px">
                <div style="padding:10px">
                  <el-form label-position="top">
                    <el-form-item label="审批结果:">
                      <el-radio-group v-model="verificationFinally" class="verification">
                        <div>
                          <el-radio :label="1">同意</el-radio></div>
                        <div>
                          <el-radio :label="2">不同意</el-radio></div>
                        <div>
                          <el-radio :label="3">驳回</el-radio></div>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注:">
                      <el-input
                        v-model="verificationOpinion"
                        type="textarea"
                        :rows="5"
                      />
                    </el-form-item>
                  </el-form>
                </div>
              </el-aside>
            </el-container>

          </el-tab-pane>
          <el-tab-pane
            label="流程信息"
            name="flow"
          >
            <el-container>
              <el-container>
                <wfFlowView :scheme-conent="schemeConent" :activity-id="activityId" />
              </el-container>
              <el-aside v-if="dialogAction !== 'create'" width="300px">
                <wfTransitionHistory :transition-history="transitionHistory" />
              </el-aside>
            </el-container>
          </el-tab-pane>
        </el-tabs>

        <div slot="footer">
          <el-button
            size="small"
            @click="closeDialog"
          >{{ L('Cancel') }}</el-button>
          <el-button
            size="small"
            type="primary"
            :loading="dialogLoading"
            :disabled="isSaveDisabled"
            @click="onApplyOrVerification"
          >
            <svg-icon icon-class="save" /> {{ L('OK') }}</el-button>
        </div></el-dialog>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import PagedFilterAndSortedRequest from '@/store/entities/pagedFilterAndSortedRequest'
import wfFlowView from './WfFlowView'
import wfTransitionHistory from './WfTransitionHistory'
import wfStatus from './WfStatus'
import { getFlowSchemeForEdit } from '@/api/flowSheme'
import { createInstance, verification, getFlowInstanceForEdit, queryHistories } from '@/api/flowInstance'
import { getUsers } from '@/api/user'

export default {
  name: 'CrudCodeBuild',
  directives: { waves },
  components: { wfFlowView, wfTransitionHistory, wfStatus },
  props: {
    tableType: {
      type: String,
      default: 'mine'
    },
    schemeId: {
      type: String,
      default: null
    },
    entityName: {
      type: String,
      default: ''
    },
    requestParam: {
      type: Object,
      default: () => { return {} }
    },
    keywordPlaceholder: {
      type: String,
      default: 'Keyword'
    },
    isShowFilterContainer: {
      type: Boolean,
      default: true
    },
    isShowEditDeleteButton: {
      type: Boolean,
      default: true
    },

    dialogEnity: {
      type: Object,
      default: () => { return {} }
    },

    dialogOptins: {
      type: Object,
      default: () => {
        return {
          createEnityParam: {},
          createTitle: 'Create',
          editTitle: 'Edit',
          deleteConfirm: 'DeleteConfirm'
        }
      }
    }
  },
  data() {
    return {
      rdn: 0,
      pagerequest: { ...PagedFilterAndSortedRequest },
      activeSelected: null,
      creationTime: [],

      dialogCreateOrEditVisible: false,
      dialogAction: '',
      dialogLoading: false,

      activeTag: 'form',
      verificationFinally: 1,
      verificationOpinion: '',
      verificationVisible: false,
      isSaveDisabled: true,

      activityId: null,
      activityName: '',
      makerList: '',
      schemeConent: null,
      transitionHistory: [],

      originalEntity: null,
      finallyEntity: null,

      isFinish: 1,

      wfStatusOptions: [{ label: '正在运行', value: 0 }, { label: '审批通过', value: 1 }, { label: '不同意', value: 3 }, { label: '被驳回', value: 4 }]
    }
  },
  computed: {
    tableHeight() {
      return (document.body.clientHeight - 183) + 'px'
    },
    containerHeight() {
      return (document.body.clientHeight - 230) + 'px'
    },
    dialogTitle() {
      return this.dialogAction === 'create' ? '新的申请' : '流程处理'
    },
    list() {
      return this.$store.state[this.entityName].list
    },
    totalCount() {
      return this.$store.state[this.entityName].totalCount
    },
    currentPage() {
      return this.$store.state[this.entityName].currentPage
    },
    pageSize() {
      return this.$store.state[this.entityName].pageSize
    },
    loading() {
      return this.$store.state[this.entityName].loading
    }
  },
  async created() {
    this.$store.commit(`${this.entityName}/SET_ENTITY_NAME`, this.entityName)
    this.pageChange(1)
  },
  methods: {
    isActiveNo(nodeName = '') {
      return this.dialogAction === 'create' && nodeName === this.activityName ? this.rdn : 0
    },
    isActiveNode(nodeName = '') {
      if (this.dialogAction === 'create') {
        return nodeName === this.activityName ? this.rdn : 0
      } else {
        return this.verificationVisible && nodeName !== '' && nodeName === this.activityName ? this.rdn : 0
      }
    },
    handleComand(command, row) {
      switch (command) {
        case 'edit':
          this.edit(row)
          break
        case 'delete':
          this.deleteItem(row)
          break
      }
    },
    tableSortChange(column) {
      this.pageChange(1)
      if (column.order === 'descending') {
        this.pagerequest.sorting = `${column.prop} desc`
      } else {
        this.pagerequest.sorting = `${column.prop} asc`
      }
      if (!column.prop) { this.pagerequest.sorting = '' }
      this.getpage()
    },

    edit(row) {
      this.openDialog(row, 'edit')
    },

    onCreate() {
      this.openDialog(this.dialogOptins.createEnityParam, 'create')
    },

    async deleteItem(row) {
      this.$confirm(this.L(this.dialogOptins.deleteConfirm), this.L('Tips'), {
        confirmButtonText: this.L('Yes'),
        cancelButtonText: this.L('No'),
        type: 'warning'
      })
        .then(async() => {
          await this.$store.dispatch({
            type: `${this.entityName}/deleteItem`,
            data: row
          })
          await this.getpage()
          this.$message({
            type: 'success',
            message: this.L('DeleteSuccessfully')
          })
        })
    },
    async getpage() {
      this.pagerequest.type = this.tableType
      this.pagerequest.maxResultCount = this.pageSize
      this.pagerequest.skipCount = (this.currentPage - 1) * this.pageSize
      // filters
      for (var i in this.requestParam) {
        this.pagerequest[i] = this.requestParam[i]
      }
      await this.$store.dispatch({
        type: `${this.entityName}/load`,
        data: this.pagerequest
      })
    },
    pageChange(page) {
      this.$store.commit(`${this.entityName}/SET_CURRENT_PAGE`, page)
      this.getpage()
    },
    pagesizeChange(pagesize) {
      this.$store.commit(`${this.entityName}/SET_PAGE_SIZE`, pagesize)
      this.getpage()
    },

    // 添加编辑对话框方法
    async openDialog(enity, action) {
      this.rdn = Math.random()
      this.dialogCreateOrEditVisible = true
      this.dialogAction = action
      this.isFinish = 1
      this.activityName = ''
      this.makerList = ''
      this.makerIdList = ''
      this.activeTag = 'form'

      this.verificationFinally = 1
      this.verificationOpinion = ''

      // 回调表单验证清除
      this.$nextTick(async() => {
        this.$emit('dialogFormClearValidate')
      })

      this.originalEntity = Object.assign({}, enity) // copy obj
      this.verificationVisible = false
      this.isSaveDisabled = true

      if (action === 'create') {
        this.$emit('update:dialogEnity', { ...this.originalEntity })

        var resp = await getFlowSchemeForEdit({ id: this.schemeId })
        var schemeStr = resp.data.result && resp.data.result.flowScheme && resp.data.result.flowScheme.schemeContent || ''
        this.schemeConent = JSON.parse(schemeStr)
        this.activityId = null
        this.transitionHistory = []
        this.isSaveDisabled = false
      }

      if (action === 'edit') {
        this.originalEntity = await this.$store.dispatch({
          type: `${this.entityName}/getForEdit`,
          data: { id: this.originalEntity.id }
        })
        this.$emit('update:dialogEnity', Object.assign({}, this.originalEntity))

        var resp1 = await getFlowInstanceForEdit({ id: this.originalEntity.flowInstanceId })
        var flowInstance1 = resp1.data.result && resp1.data.result.flowInstance
        var schemeStr1 = flowInstance1 && flowInstance1.schemeContent || ''

        this.verificationVisible = (flowInstance1.isFinish === 0 || flowInstance1.isFinish === 4) && (`,${flowInstance1.makerList},`.indexOf(`${this.$store.state.session.user.id},`) > -1)
        this.isSaveDisabled = !this.verificationVisible
        if (!this.verificationVisible) this.rdn = 0 // 无权限时，控件不可编辑状态

        this.isFinish = flowInstance1.isFinish
        if ([0, 4].indexOf(flowInstance1.isFinish) > -1) { // 审批通过 不同意
          var usersResp = await getUsers({ uids: flowInstance1.makerList })
          var usersResult = usersResp.data.result.items.map(u => u.name)
          this.makerList = usersResult.join(',')
        }
        this.schemeConent = JSON.parse(schemeStr1)

        this.activityId = flowInstance1 && flowInstance1.activityId || null
        this.activityName = flowInstance1.isFinish === 4 ? '' : flowInstance1 && flowInstance1.activityName || ''
        // console.log(1, this.activityName, this.rdn)
        // todo: 获取流转历史记录
        var respHIs = await queryHistories({ instanceId: this.originalEntity.flowInstanceId })
        this.transitionHistory = respHIs.data && respHIs.data.result && respHIs.data.result.items || []
      }
      // this.$refs[`${this.entityName}Form`].clearValidate()
    },
    closeDialog() {
      this.dialogCreateOrEditVisible = false
    },

    onApplyOrVerification() {
      if (!!this.dialogEnity.id && this.dialogAction === 'edit') {
        this.$emit('dialogFormValidate', async val => {
          if (val) {
            this.dialogLoading = true
            this.CompareEntity()
            var payload = { flowInstanceId: this.originalEntity.flowInstanceId,
              verificationFinally: this.verificationFinally,
              verificationOpinion: this.verificationOpinion,
              frmData: JSON.stringify(this.originalEntity),
              updateFrmData: JSON.stringify(this.finallyEntity) }
            // console.log(payload)
            await verification(payload).finally(() => { this.dialogLoading = false })
            this.dialogLoading = false
            this.getpage()
            this.closeDialog()
          }
        })
      } else {
        this.$emit('dialogFormValidate', async val => {
          if (val) {
            this.dialogLoading = true
            await createInstance({
              SchemeId: this.schemeId,
              FrmData: JSON.stringify(this.dialogEnity) }).finally(() => { this.dialogLoading = false })
            this.$message({
              type: 'success',
              message: this.L('SavedSuccessfully')
            })
            this.getpage()
            this.closeDialog()
          }
        })
      }
    },
    CompareEntity() {
      // 比较获取变化部分的entity
      this.finallyEntity = {}
      for (var p in this.dialogEnity) {
        if (this.dialogEnity[p] === this.originalEntity[p]) continue
        this.finallyEntity[p] = this.dialogEnity[p]
      }
      this.finallyEntity['id'] = this.dialogEnity['id']
      // console.log(0, this.dialogEnity, this.originalEntity, this.finallyEntity)
    }
  }
}
</script>
<style lang="scss" scoped>
.verification {
  div{
    margin:10px 0
  }
}
</style>
